package com.uinnova.product.eam.service.impl;

import com.alibaba.fastjson.JSON;
import com.binary.core.exception.BinaryException;
import com.binary.framework.web.RemoteResult;
import com.binary.jdbc.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.uinnova.product.cj.feign.dto.PlanDesignInstanceDTO;
import com.uinnova.product.eam.base.util.EamUtil;
import com.uinnova.product.eam.comm.exception.BusinessException;
import com.uinnova.product.eam.comm.model.es.EamNoticeKeyword;
import com.uinnova.product.eam.comm.model.es.WorkbenchChargeDone;
import com.uinnova.product.eam.feign.workable.FlowableFeign;
import com.uinnova.product.eam.feign.workable.entity.TaskResponse;
import com.uinnova.product.eam.model.cj.domain.PlanDesignInstance;
import com.uinnova.product.eam.model.constants.FlowableConstant;
import com.uinnova.product.eam.model.vo.WorkbenchBO;
import com.uinnova.product.eam.model.vo.WorkbenchChargeDoneVO;
import com.uinnova.product.eam.service.WorkbenchChargeDoneSvc;
import com.uinnova.product.eam.service.cj.service.PlanDesignInstanceService;
import com.uinnova.product.eam.service.es.WorkbenchChargeDoneDao;
import com.uinnova.product.eam.service.todo.GTJobSvc;
import com.uinnova.product.eam.service.todo.dto.GTDeletePendingJobInfo;
import com.uinnova.product.eam.service.todo.dto.GTFinishPendingJobInfo;
import com.uinnova.product.eam.service.todo.dto.GTSendPendingJobInfo;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.query.CSysUser;
import com.uino.dao.permission.ESUserSvc;
import com.uino.dao.util.ESUtil;
import com.uino.util.sys.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WorkbenchChargeDoneSvcImpl implements WorkbenchChargeDoneSvc {

    @Autowired
    private WorkbenchChargeDoneDao workbenchChargeDoneDao;

    @Resource
    private PlanDesignInstanceService planDesignInstanceService;
    @Autowired
    private FlowableFeign flowableFeign;

    @Autowired
    private ESUserSvc userSvc;
    @Autowired
    private GTJobSvc gtJobSvc;
    @Value("${http.resource.space}")
    private String httpPath;
    @Value("${gt.data.imitate:false}")
    private Boolean gtDataImitate;

    private static final String TAG_PLAN = "plan";
    private static final String TAG_DIAGRAM = "diagram";

    private static final String SOURCE_TYPE = "sourceType";
    private static final String PLAN_ID = "planId";


    @Override
    public Boolean saveOrUpdate(List<WorkbenchChargeDone> workbenchChargeDoneList) {
        if (workbenchChargeDoneList == null || workbenchChargeDoneList.size() < 1) {
            return true;
        }
        List<String> businessIdList = workbenchChargeDoneList.stream().filter(item -> item.getBusinessId() != null).map(item -> item.getBusinessId()).distinct().collect(Collectors.toList());

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termsQuery("businessId.keyword",businessIdList));
        List<WorkbenchChargeDone> queryList = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        if (queryList == null || queryList.size() < 1) {
            //全量保存
            for (WorkbenchChargeDone workbenchChargeDone : workbenchChargeDoneList) {
                workbenchChargeDone.setId(ESUtil.getUUID());
                workbenchChargeDone.setDomainId(1L);
                workbenchChargeDone.setCreateTime(ESUtil.getNumberDateTime());
                workbenchChargeDone.setModifyTime(ESUtil.getNumberDateTime());
            }
            sendGTJob(workbenchChargeDoneList, 1);
            workbenchChargeDoneDao.saveOrUpdateBatch(workbenchChargeDoneList);
        }else{
            //幂等性处理在保存
            List<WorkbenchChargeDone> insertList = Lists.newArrayList();
            List<String> filterBusinessIdList = queryList.stream().map(item -> item.getBusinessId()).collect(Collectors.toList());
            for (WorkbenchChargeDone workbenchChargeDone : workbenchChargeDoneList) {
                if (!filterBusinessIdList.contains(workbenchChargeDone.getBusinessId())) {
                    insertList.add(workbenchChargeDone);
                }
            }
            if (!CollectionUtils.isEmpty(insertList)) {
                for (WorkbenchChargeDone workbenchChargeDone : insertList) {
                    workbenchChargeDone.setId(ESUtil.getUUID());
                    workbenchChargeDone.setDomainId(1l);
                    workbenchChargeDone.setCreateTime(ESUtil.getNumberDateTime());
                    workbenchChargeDone.setModifyTime(ESUtil.getNumberDateTime());
                }
                sendGTJob(insertList, 1);
                workbenchChargeDoneDao.saveOrUpdateBatch(insertList);
            }
        }
        return true;
    }

    private void sendGTJob(List<WorkbenchChargeDone> workbenchChargeDoneList, Integer todoType) {
        if (gtDataImitate) {
            return;
        }
        for (WorkbenchChargeDone done : workbenchChargeDoneList) {
            if (gtJobIngore(done) || Boolean.TRUE.equals(done.getStartProcess())) {
                continue;
            }
            GTSendPendingJobInfo sendPendingJobInfo = new GTSendPendingJobInfo();
            sendPendingJobInfo.setNotifyId(done.getId().toString());
            sendPendingJobInfo.setSubject(done.getProcessInstanceName());
            sendPendingJobInfo.setLink(getPCLink(done));
            sendPendingJobInfo.setMobileLink(getMobileLink(done));
            sendPendingJobInfo.setTargets(Arrays.asList(done.getUserId()));
            sendPendingJobInfo.setCreator(done.getSubmitter());
            sendPendingJobInfo.setTodoType(todoType);
            sendPendingJobInfo.setTodoLevel(3);
            boolean success;
            try {
                log.info("推送门户待办:{}", JSON.toJSONString(sendPendingJobInfo));
                success = gtJobSvc.sendPendingJob(sendPendingJobInfo);
                log.info("推送门户待办结果:{}", success);
            } catch (Exception e) {
                log.info("推送门户待办失败:{}", JSON.toJSONString(e));
                success = false;
            }
            if (!success) {
                log.error("推送门户待办失败");
            } else {
                done.setNotifyId(sendPendingJobInfo.getNotifyId());
            }
        }
    }

    private String getPCLink(WorkbenchChargeDone done) {
        String baseUrl =  httpPath.replace("/tarsier-eam", "").replace("/rsm", "");
        //传阅
        if (done.getType() != null && done.getType() == 6) {
            return baseUrl.concat("/approval-page#/ArchSchemeApproveDetail")
                    .concat("/").concat(done.getBusinessKey())
                    .concat("?todoId=").concat(done.getId().toString())
                    .concat("&todoType=6");
        }
        if (FlowableConstant.GT_TECHNICAL_SCHEME_APPROVE.equals(done.getProcessDefinitionKey())) {
            return baseUrl.concat("/approval-page#/ArchSchemeApprove")
                    .concat("?todoId=").concat(done.getId().toString())
                    .concat("&processInstanceId=").concat(done.getProcessInstanceId())
                    .concat("&businessKey=").concat(done.getBusinessKey())
                    .concat("&taskDefinitionKey=").concat(done.getTaskDefinitionKey())
                    .concat("&description=").concat(done.getDescription())
                    .concat("&taskId=").concat(done.getTaskId())
                    .concat("&category=").concat(done.getCategory());
        }
        if (FlowableConstant.GT_ASSERT_APPROVE.equals(done.getProcessDefinitionKey())) {
            if (StringUtils.isBlank(done.getDescription())) {
                done.setDescription("-");
            }
            return baseUrl.concat("/approval-page#/ArchSchemeAssetApprove")
                    .concat("?todoId=").concat(done.getId().toString())
                    .concat("&processInstanceId=").concat(done.getProcessInstanceId())
                    .concat("&businessKey=").concat(done.getBusinessKey())
                    .concat("&taskDefinitionKey=").concat(done.getTaskDefinitionKey())
                    .concat("&description=").concat(done.getDescription())
                    .concat("&taskId=").concat(done.getTaskId())
                    .concat("&type=7")
                    .concat("&category=").concat(done.getCategory());
        }
        return baseUrl.concat("/approval-page#/ArchSchemeDiagramApprove")
                .concat("?todoId=").concat(done.getId().toString())
                .concat("&taskId=").concat(done.getTaskId())
                .concat("&processInstanceId=").concat(done.getProcessInstanceId())
                .concat("&businessKey=").concat(done.getBusinessKey())
                .concat("&type=").concat(done.getType() + "");
    }

    private String getMobileLink(WorkbenchChargeDone done) {
        String baseUrl =  httpPath.replace("/tarsier-eam", "").replace("/rsm", "");
        //传阅
        if (done.getType() != null && done.getType() == 6) {
            return baseUrl.concat("/approval-mobile#/ApprovalDeliverableDetail")
                    .concat("/").concat(done.getBusinessKey())
                    .concat("?todoId=").concat(done.getId().toString())
                    .concat("&todoType=6");
        }
        if (FlowableConstant.GT_TECHNICAL_SCHEME_APPROVE.equals(done.getProcessDefinitionKey())) {
            return baseUrl.concat("/approval-mobile#/deliverable")
                    .concat("?todoId=").concat(done.getId().toString())
                    .concat("&processInstanceId=").concat(done.getProcessInstanceId())
                    .concat("&businessKey=").concat(done.getBusinessKey())
                    .concat("&taskDefinitionKey=").concat(done.getTaskDefinitionKey())
                    .concat("&description=").concat(done.getDescription())
                    .concat("&taskId=").concat(done.getTaskId())
                    .concat("&category=").concat(done.getCategory());
        }
        if (FlowableConstant.GT_ASSERT_APPROVE.equals(done.getProcessDefinitionKey())) {
            return baseUrl.concat("/approval-mobile#/ArchSchemeApproveToPC")
                    .concat("/1?circulateId=1");
        }
        return baseUrl.concat("/approval-mobile#/diagram")
                .concat("?todoId=").concat(done.getId().toString())
                .concat("&taskId=").concat(done.getTaskId())
                .concat("&processInstanceId=").concat(done.getProcessInstanceId())
                .concat("&businessKey=").concat(done.getBusinessKey())
                .concat("&type=").concat(done.getType() + "");
    }

    @Override
    public boolean changeAction(String taskId) {
        WorkbenchChargeDone workbenchChargeDone = new WorkbenchChargeDone();
        workbenchChargeDone.setTaskId(taskId);
        List<WorkbenchChargeDone> queryList = workbenchChargeDoneDao.getListByCdt(workbenchChargeDone);
        if (queryList == null || queryList.size() < 1) {
            return false;
        }
        for (WorkbenchChargeDone chargeDone : queryList) {
            if (chargeDone.getAction() == 1 || chargeDone.getAction() == 3) {
                chargeDone.setAction(2);
                chargeDone.setModifyTime(ESUtil.getNumberDateTime());
                chargeDone.setTaskEndTime(new Date());
            }else{
                continue;
            }
        }
        workbenchChargeDoneDao.saveOrUpdateBatch(queryList);
        finishGTJob(queryList);
        return true;
    }

    private void finishGTJob(List<WorkbenchChargeDone> workbenchChargeDoneList) {
        if (gtDataImitate) {
            return;
        }
        for (WorkbenchChargeDone done : workbenchChargeDoneList) {
            if (gtJobIngore(done) || StringUtils.isBlank(done.getNotifyId())) {
                continue;
            }
            try {
                GTFinishPendingJobInfo finishPendingJobInfo = new GTFinishPendingJobInfo();
                finishPendingJobInfo.setNotifyId(done.getNotifyId());
                log.info("关闭门户待办:{}", JSON.toJSONString(finishPendingJobInfo));
                boolean success = gtJobSvc.finishPendingJob(finishPendingJobInfo);
                log.info("关闭门户待办结果:{}", success);
            } catch (Exception e) {
                log.info("关闭门户待办失败:{}", JSON.toJSONString(e));
            }
        }
    }

    private Boolean gtJobIngore(WorkbenchChargeDone done) {
        //传阅待办
        if (done.getType() != null && done.getType() == 6) {
            return false;
        }
        //国投架构评审待办、国投视图审批待办
        return !FlowableConstant.GT_TECHNICAL_SCHEME_APPROVE.equals(done.getProcessDefinitionKey())
                && !FlowableConstant.GT_DIAGRAM_APPROVE.equals(done.getProcessDefinitionKey())
                && !FlowableConstant.GT_ASSERT_APPROVE.equals(done.getProcessDefinitionKey());
    }

    private void deleteGTDoneJob(List<WorkbenchChargeDone> workbenchChargeDoneList) {
        if (gtDataImitate) {
            return;
        }
        for (WorkbenchChargeDone done : workbenchChargeDoneList) {
            if (!FlowableConstant.GT_TECHNICAL_SCHEME_APPROVE.equals(done.getProcessDefinitionKey())
                    && !FlowableConstant.GT_DIAGRAM_APPROVE.equals(done.getProcessDefinitionKey())
                    && !FlowableConstant.GT_ASSERT_APPROVE.equals(done.getProcessDefinitionKey())) {
                continue;
            }
            if (StringUtils.isBlank(done.getNotifyId())) {
                continue;
            }
            try {
                GTDeletePendingJobInfo deletePendingJobInfo = new GTDeletePendingJobInfo();
                deletePendingJobInfo.setNotifyId(done.getNotifyId());
                log.info("删除门户已办:{}", JSON.toJSONString(deletePendingJobInfo));
                boolean success = gtJobSvc.deleteDoneJob(deletePendingJobInfo);
                log.info("删除门户已办结果:{}", success);
            } catch (Exception e) {
                log.info("删除门户已办失败:{}", JSON.toJSONString(e));
            }
        }
    }

    private void deleteGTTodoJob(List<WorkbenchChargeDone> workbenchChargeDoneList) {
        if (gtDataImitate) {
            return;
        }
        for (WorkbenchChargeDone done : workbenchChargeDoneList) {
            if (!FlowableConstant.GT_TECHNICAL_SCHEME_APPROVE.equals(done.getProcessDefinitionKey())
                    && !FlowableConstant.GT_DIAGRAM_APPROVE.equals(done.getProcessDefinitionKey())
                    && !FlowableConstant.GT_ASSERT_APPROVE.equals(done.getProcessDefinitionKey())) {
                continue;
            }
            if (StringUtils.isBlank(done.getNotifyId())) {
                continue;
            }
            try {
                GTDeletePendingJobInfo deletePendingJobInfo = new GTDeletePendingJobInfo();
                deletePendingJobInfo.setNotifyId(done.getNotifyId());
                log.info("删除门户待办:{}", JSON.toJSONString(deletePendingJobInfo));
                boolean success = gtJobSvc.deleteTodoJob(deletePendingJobInfo);
                log.info("删除门户待办结果:{}", success);
            } catch (Exception e) {
                log.info("删除门户待办失败:{}", JSON.toJSONString(e));
            }
        }
    }

    @Override
    public Page<WorkbenchChargeDone> pageQueryList(Integer pageNum, Integer pageSize, Integer action) {
        // 增加 [action = 99] 类型 查询我发起的视图/方案评审流程
        Boolean isStart = false; //是否查我发起的
        if (action != null && 99 == action.intValue()) {
            action = 2;
            isStart = true;
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("action",action));
        boolQueryBuilder.must(QueryBuilders.termQuery("userId.keyword",SysUtil.getCurrentUserInfo().getLoginCode()));
        boolQueryBuilder.mustNot(QueryBuilders.termQuery("processDefinitionKey.keyword", FlowableConstant.DECISION_DEFINITION_KEY));
        if (isStart) {
            boolQueryBuilder.must(QueryBuilders.termQuery("submitter.keyword",SysUtil.getCurrentUserInfo().getLoginCode()));
            boolQueryBuilder.must(QueryBuilders.termQuery("startProcess",true));
        }
        long count = workbenchChargeDoneDao.countByCondition(boolQueryBuilder);
        Page<WorkbenchChargeDone> queryPage;
        if (count == 0) {
            return null;
        }
        List<SortBuilder<?>> sorts = new LinkedList<>();
        if (action == 1) {
            sorts.add(SortBuilders.fieldSort("taskCreateTime").order(SortOrder.DESC));
        } else if (isStart) {
            sorts.add(SortBuilders.fieldSort("processStartTime").order(SortOrder.DESC));
        } else {
            sorts.add(SortBuilders.fieldSort("taskEndTime").order(SortOrder.DESC));
        }
        queryPage = workbenchChargeDoneDao.getSortListByQuery(pageNum, pageSize, boolQueryBuilder, sorts);

        if (queryPage == null || queryPage.getData() == null) {
            return new Page<>();
        }

        List<WorkbenchChargeDone> data = queryPage.getData();

        //转换用户信息
        convertTaskUserName(data);
        //处理已办“待处理人”
        dealDoneTaskCurrentAssignees(data);
        if (isStart) {
            // 我提交的 处理当前流程节点
            dealTaskCurrentStage(data);

        }
        queryPage.setData(data);
        return queryPage;
    }

    private void dealDoneTaskCurrentAssignees(List<WorkbenchChargeDone> datas) {
        List<String> processInstanceIds = datas.stream()
                .filter(data -> data.getType() != null && data.getType() != 2)
                .filter(data -> data.getProcessInstanceId() != null)
                .map(WorkbenchChargeDone::getProcessInstanceId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(processInstanceIds)) {
            return;
        }
        List<TaskResponse> taskResponses = flowableFeign.getDoneTaskList(SysUtil.getCurrentUserInfo().getLoginCode(), processInstanceIds);
        Set<String> userIdSet = Sets.newHashSet();
        for (TaskResponse taskRespons : taskResponses) {
            userIdSet.add(taskRespons.getUserId());
            userIdSet.add(taskRespons.getSubmitter());
            if (StringUtils.isNotBlank(taskRespons.getCurrentAssignees()) && !"-".equals(taskRespons.getCurrentAssignees())) {
                String[] split = taskRespons.getCurrentAssignees().split(",");
                userIdSet.addAll(Arrays.asList(split));
            }
        }
        Map<String, SysUser> sysUserMap = getStringSysUserMap(userIdSet);
        Map<String, String> processIdWithCurrentAssingees = new ConcurrentHashMap<>();
        Map<String, String> processIdWithCategory = new ConcurrentHashMap<>();
        for (TaskResponse taskRespons : taskResponses) {
            if (StringUtils.isNotBlank(taskRespons.getCurrentAssignees()) && !"-".equals(taskRespons.getCurrentAssignees())) {
                String[] split = taskRespons.getCurrentAssignees().split(",");
                Set<String> collect = Arrays.stream(split).filter(s -> sysUserMap.get(s) != null)
                        .map(s -> sysUserMap.get(s).getUserName()).collect(Collectors.toSet());
                taskRespons.setCurrentAssignees(StringUtils.join(collect, ","));
            }
            String key = taskRespons.getProcessInstanceId() + taskRespons.getTaskDefinitionKey();
            processIdWithCurrentAssingees.put(key, taskRespons.getCurrentAssignees());
            processIdWithCategory.put(key, taskRespons.getCategory());
        }
        for (WorkbenchChargeDone data : datas) {
            if (StringUtils.isBlank(data.getProcessInstanceId())) {
                continue;
            }
            String key = data.getProcessInstanceId() + data.getTaskDefinitionKey();
            if (processIdWithCurrentAssingees.containsKey(key)) {
                String currentAssingees = processIdWithCurrentAssingees.get(key);
                data.setCurrentAssignees("-".equals(currentAssingees) ? "流程结束" : currentAssingees);
                data.setCategory(processIdWithCategory.get(key));
            }
        }
    }

    private void dealTaskCurrentStage(List<WorkbenchChargeDone> datas) {
        List<String> processInstanceIds = datas.stream()
                .filter(data -> data.getType() != null && data.getType() != 2)
                .filter(data -> data.getProcessInstanceId() != null)
                .map(WorkbenchChargeDone::getProcessInstanceId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(processInstanceIds)) {
            return;
        }
        Map<String, List<TaskResponse>> activeTaskMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(processInstanceIds)) {
            List<TaskResponse> tasks = flowableFeign.getActiveSimpleTaskByProcessInstanceIds(processInstanceIds);
            if (!CollectionUtils.isEmpty(tasks)) {
                tasks.sort(Comparator.comparing(TaskResponse::getTaskCreateTime));
                activeTaskMap = tasks.stream().collect(Collectors.groupingBy(TaskResponse::getProcessInstanceId));
            }
        }

        for (WorkbenchChargeDone data : datas) {
            data.setStage(getCurrentStage(data.getProcessInstanceId(), activeTaskMap));
            data.setCurrentAssignees("流程结束".equals(data.getCurrentAssignees()) ? "-" : data.getCurrentAssignees());
            data.setAction(99);
        }
    }

    /**
     * 获取当前流程节点
     * @return
     */
    private String getCurrentStage(String processInstanceId, Map<String, List<TaskResponse>> activeTaskMap) {
        //当前节点
        String stage = "-";
        if (StringUtils.isNotBlank(processInstanceId) &&
                activeTaskMap.containsKey(processInstanceId)) {
            List<TaskResponse> tasks = activeTaskMap.get(processInstanceId);
            List<String> names = new ArrayList<>();
            for (TaskResponse task : tasks) {
                String name = task.getTaskName();
                if (StringUtils.isNotBlank(name) && !names.contains(name)) {
                    names.add(name);
                }
            }
            if (!CollectionUtils.isEmpty(names)) {
                stage = String.join(",", names);
            }
        }
        return stage;
    }

    @Override
    public RemoteResult transform(String businessId,String transId,Integer dirType) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("businessId.keyword",businessId));
        List<WorkbenchChargeDone> workbenchChargeDoneList = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        WorkbenchChargeDone workbenchChargeDone = workbenchChargeDoneList.get(0);



        List<EamNoticeKeyword> keywords = workbenchChargeDone.getKeywords();
        String transPlanId = null;
        for (EamNoticeKeyword keyword : keywords) {
            Map<String, Object> params = keyword.getParams();
            if (Integer.valueOf(params.get(SOURCE_TYPE).toString()) == 0) {
                continue;
            }
            try {
                Long.valueOf(params.get(PLAN_ID).toString());
                continue;
            } catch (Exception e) {}
            String businssKey = params.get(PLAN_ID).toString();
            if (!transId.equals(businssKey)) {
                continue;
            }
            //通过businessKey + dirType获取最新版本方案
            PlanDesignInstanceDTO planInstance = planDesignInstanceService.getAssetsLatestPlan(businssKey, null);
            if (planInstance == null) {
                return new RemoteResult(false, 30001, "方案已被删除");
            }
            transPlanId = planInstance.getId().toString();
        }
        return new RemoteResult(transPlanId);
    }

    @Override
    public WorkbenchBO getCount() {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("userId.keyword",SysUtil.getCurrentUserInfo().getLoginCode()));
        List<WorkbenchChargeDone> queryList = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        if (queryList == null || queryList.size() < 1) {
            return new WorkbenchBO();
        }
        WorkbenchBO workbenchBO = new WorkbenchBO();
        List<WorkbenchChargeDone> todoList = queryList.stream().filter(item -> item.getAction().equals(1)).collect(Collectors.toList());
        List<WorkbenchChargeDone> doList = queryList.stream().filter(item -> item.getAction().equals(2)).collect(Collectors.toList());
        List<WorkbenchChargeDone> submitList = queryList.stream().filter(item -> item.getAction().equals(2) &&
                item.getSubmitter().equals(SysUtil.getCurrentUserInfo().getLoginCode()) &&
                (item.getStartProcess() != null && item.getStartProcess())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(todoList)) {
            workbenchBO.setTodoCount(todoList.size());
        }
        if (!CollectionUtils.isEmpty(doList)) {
            workbenchBO.setDoneCount(doList.size());
        }
        if (!CollectionUtils.isEmpty(submitList)) {
            workbenchBO.setSubmitCount( submitList.size());
        }
        return workbenchBO;
    }

    @Override
    public boolean updateInfoStatus(Long planId, String diagramId, Integer type) {
        String planIdString = null;
        PlanDesignInstanceDTO planForFeign = null;
        PlanDesignInstance planDesignInstance = planDesignInstanceService.getPlanDesignInstance(planId);
        if (planDesignInstance != null) {
            planForFeign = new PlanDesignInstanceDTO();
            BeanUtils.copyProperties(planDesignInstance, planForFeign);
        }
        if (planForFeign != null && planForFeign.getAssetsType() == 1) {
            planIdString = planForFeign.getId().toString();
        }
        if (planForFeign != null && planForFeign.getAssetsType() == 2) {
            planIdString = planForFeign.getBusinessKey();
        }
        if (type == 1) {
            //表示全部更新
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery("planId.keyword",planIdString));
            boolQueryBuilder.must(QueryBuilders.termQuery("action",1));
            boolQueryBuilder.must(QueryBuilders.termQuery("userId.keyword",SysUtil.getCurrentUserInfo().getLoginCode()));
            List<WorkbenchChargeDone> queryList = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
            for (WorkbenchChargeDone workbenchChargeDone : queryList) {
                workbenchChargeDone.setAction(2);
                workbenchChargeDone.setTaskEndTime(new Date());
            }
            workbenchChargeDoneDao.saveOrUpdateBatch(queryList);
        }else{
            //只更新单图的
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery("planId.keyword",planIdString));
            boolQueryBuilder.must(QueryBuilders.termQuery("action",1));
            boolQueryBuilder.must(QueryBuilders.termQuery("userId.keyword",SysUtil.getCurrentUserInfo().getLoginCode()));
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("diagramIds.keyword",diagramId));
            List<WorkbenchChargeDone> queryList = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
            for (WorkbenchChargeDone workbenchChargeDone : queryList) {
                workbenchChargeDone.setAction(2);
                workbenchChargeDone.setTaskEndTime(new Date());
            }
            workbenchChargeDoneDao.saveOrUpdateBatch(queryList);
        }
        return true;
    }

    @Override
    public void deleteWorkbenchChargeDone(WorkbenchChargeDoneVO workbenchChargeDoneVO) {
        List<Long> deleteDafPlanIdList = workbenchChargeDoneVO.getDeleteDafPlanIdList();
        List<String> deletePublishPlanIdList = workbenchChargeDoneVO.getDeletePublishPlanIdList();
        if (!CollectionUtils.isEmpty(deleteDafPlanIdList)) {
            List<String> changeDeleteDafPlanIdList = deleteDafPlanIdList.stream().map(item -> item + "").collect(Collectors.toList());
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termsQuery("planId.keyword",changeDeleteDafPlanIdList));
            workbenchChargeDoneDao.deleteByQuery(boolQueryBuilder,true);
        }

        if (!CollectionUtils.isEmpty(deletePublishPlanIdList)) {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termsQuery("planId.keyword",deletePublishPlanIdList));
            workbenchChargeDoneDao.deleteByQuery(boolQueryBuilder,true);
        }

    }

    @Override
    public void deleteWorkbenchPublishedChargeDone(String businessKey,Integer dirType) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("planId.keyword",businessKey));
        workbenchChargeDoneDao.deleteByQuery(boolQueryBuilder,true);
    }

    @Override
    public boolean deleteByCondition(WorkbenchChargeDone workbenchChargeDone) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(workbenchChargeDone.getProcessInstanceId())) {
            boolQueryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword",workbenchChargeDone.getProcessInstanceId()));
        }else{
            throw new BusinessException("流程实例已经删除请刷新");
        }
        boolQueryBuilder.must(QueryBuilders.termQuery("action",1));
        workbenchChargeDoneDao.deleteByQuery(boolQueryBuilder,true);
        return true;
    }

    @Override
    public Boolean batchModifyWorkbenchTask(String processInstanceId,String businessKey, String curTaskId) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(processInstanceId)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword",processInstanceId));
            if(StringUtils.isNotEmpty(businessKey)){
                //处理国投子流程
                if (businessKey.contains("_CHILD")) {
                    boolQueryBuilder.must(QueryBuilders.termQuery("gtChildBusinessKey.keyword",businessKey));
                } else {
                    boolQueryBuilder.must(QueryBuilders.termQuery("businessKey.keyword",businessKey));
                }
            }
        }else{
            log.info("工作台没有相关流程实例的代办");
        }
        boolQueryBuilder.must(QueryBuilders.termQuery("action",1));
        //排除当前操作的任务
        if (StringUtils.isNotBlank(curTaskId)) {
            boolQueryBuilder.mustNot(QueryBuilders.termQuery("taskId.keyword", curTaskId));
        }
        List<WorkbenchChargeDone> workbenchChargeDoneList = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        for (WorkbenchChargeDone workbenchChargeDone : workbenchChargeDoneList) {
            workbenchChargeDone.setAction(2);
            workbenchChargeDone.setModifyTime(ESUtil.getNumberDateTime());
            workbenchChargeDone.setTaskEndTime(new Date());
        }
        workbenchChargeDoneDao.saveOrUpdateBatch(workbenchChargeDoneList);
        finishGTJob(workbenchChargeDoneList);
        return true;
    }

    @Override
    public Boolean batchModifyWorkbenchTaskDone(String processInstanceId, String businessKey) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(processInstanceId)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword",processInstanceId));
            if(StringUtils.isNotEmpty(businessKey)){
                boolQueryBuilder.must(QueryBuilders.termQuery("businessKey.keyword",businessKey));
            }
        }else{
            log.info("工作台没有相关流程实例的代办");
        }
        boolQueryBuilder.must(QueryBuilders.termQuery("action",1));
        List<WorkbenchChargeDone> workbenchChargeDoneList = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        for (WorkbenchChargeDone workbenchChargeDone : workbenchChargeDoneList) {
            workbenchChargeDone.setAction(2);
            workbenchChargeDone.setModifyTime(ESUtil.getNumberDateTime());
            workbenchChargeDone.setTaskEndTime(new Date());
        }
        workbenchChargeDoneDao.saveOrUpdateBatch(workbenchChargeDoneList);
        finishGTJob(workbenchChargeDoneList);
        return true;
    }

    private void convertTaskUserName(List<WorkbenchChargeDone> WorkbenchChargeDoneList) {
        Set<String> userIdSet = Sets.newHashSet();
        for (WorkbenchChargeDone workbenchChargeDone : WorkbenchChargeDoneList) {
            if (workbenchChargeDone.getType() != null) {
                if (workbenchChargeDone.getType() == 2) {
                    continue;
                }
                userIdSet.add(workbenchChargeDone.getUserId());
                userIdSet.add(workbenchChargeDone.getSubmitter());
                if (StringUtils.isNotBlank(workbenchChargeDone.getCurrentAssignees()) && !"-".equals(workbenchChargeDone.getCurrentAssignees())) {
                    String[] split = workbenchChargeDone.getCurrentAssignees().split(",");
                    userIdSet.addAll(Arrays.asList(split));
                }
            }
        }
        Map<String, SysUser> sysUserMap = getStringSysUserMap(userIdSet);
        for (WorkbenchChargeDone workbenchChargeDone : WorkbenchChargeDoneList) {
            if (workbenchChargeDone.getType() != null) {
                if (workbenchChargeDone.getType() == 2) {
                    continue;
                }
                if (sysUserMap.get(workbenchChargeDone.getUserId()) != null) {
                    workbenchChargeDone.setUserId(sysUserMap.get(workbenchChargeDone.getUserId()).getUserName());
                }
                if (sysUserMap.get(workbenchChargeDone.getSubmitter()) != null) {
                    workbenchChargeDone.setSubmitter(sysUserMap.get(workbenchChargeDone.getSubmitter()).getUserName());
                }
                if (StringUtils.isNotBlank(workbenchChargeDone.getCurrentAssignees()) && !"-".equals(workbenchChargeDone.getCurrentAssignees())) {
                    String[] split = workbenchChargeDone.getCurrentAssignees().split(",");
                    List<String> collect = Arrays.stream(split).filter(s -> sysUserMap.get(s) != null)
                            .map(s -> sysUserMap.get(s).getUserName()).collect(Collectors.toList());
                    workbenchChargeDone.setCurrentAssignees(StringUtils.join(collect, ","));
                }
            }
        }
    }

    private Map<String, SysUser> getStringSysUserMap(Set<String> userIdSet) {
        if (userIdSet == null || userIdSet.size() < 1) {
            return new HashMap<String, SysUser>();
        }
        Map<String, SysUser> sysUserMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userIdSet)) {
            String[] userIds = new String[userIdSet.size()];
            userIdSet.toArray(userIds);
            CSysUser cSysUser = new CSysUser();
            cSysUser.setLoginCodes(userIds);
            int pageSize = userIdSet.size();
            if (pageSize > 20000) {
                pageSize = 20000;
            }
            Page<SysUser> userPage = userSvc.getListByCdt(1, pageSize, cSysUser);
            if (userPage != null && !CollectionUtils.isEmpty(userPage.getData())) {
                sysUserMap = userPage.getData().parallelStream().collect(Collectors.toMap(SysUser::getLoginCode, u -> u));
            }
        }
        return sysUserMap;
    }

    @Override
    public void addChangeAssigness(String taskId, String orignAssignee, String nowAssignee) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("taskId.keyword", taskId));
        boolQueryBuilder.must(QueryBuilders.termQuery("action",1));
        boolQueryBuilder.must(QueryBuilders.termQuery("userId.keyword", orignAssignee));
        List<WorkbenchChargeDone> origns = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        if (CollectionUtils.isEmpty(origns)) {
            throw new BinaryException("原待办未找到");
        }
        WorkbenchChargeDone orign = origns.get(0);
        WorkbenchChargeDone now = EamUtil.copy(orign, WorkbenchChargeDone.class);
        now.setId(ESUtil.getUUID());
        now.setCreateTime(ESUtil.getNumberDateTime());
        now.setProcessStartTime(new Date());
        now.setTaskCreateTime(new Date());
        now.setCurrentAssignees(now.getCurrentAssignees().replace(orignAssignee, nowAssignee));
        now.setSubmitter(SysUtil.getCurrentUserInfo().getLoginCode());
        now.setUserId(nowAssignee);
        now.setModifier(SysUtil.getCurrentUserInfo().getLoginCode());
        now.setModifyTime(ESUtil.getNumberDateTime());
        orign.setAction(2);
        orign.setTaskEndTime(new Date());
        workbenchChargeDoneDao.saveOrUpdateBatch(Arrays.asList(orign, now));
        sendGTJob(Arrays.asList(now), 1);
        finishGTJob(Arrays.asList(orign));
    }


    /**
     * 关闭所有原待办并添加新待办
     * @param taskIdList
     * @param orignAssignee
     * @param nowAssignee
     */
    @Override
    public void closeChangeAssigness(Set<String> taskIdList, String orignAssignee, String nowAssignee) {
        log.info("开始处理任务转派，taskIdList={}, originAssignee={}, nowAssignee={}", taskIdList, orignAssignee, nowAssignee);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termsQuery("taskId.keyword", taskIdList));
        boolQueryBuilder.must(QueryBuilders.termQuery("action", 1));

        List<WorkbenchChargeDone> origns = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        if (CollectionUtils.isEmpty(origns)) {
            throw new BinaryException("原待办未找到");
        }

        List<WorkbenchChargeDone> saveOrUpdateList = new ArrayList<>();
        List<WorkbenchChargeDone> newTasks = new ArrayList<>();
        List<WorkbenchChargeDone> finishedTasks = new ArrayList<>();

        for (WorkbenchChargeDone origin : origns) {
            origin.setAction(2);
            origin.setTaskEndTime(new Date());
            saveOrUpdateList.add(origin);
            finishedTasks.add(origin);

            if (origin.getUserId().equals(orignAssignee)) {
                WorkbenchChargeDone now = EamUtil.copy(origin, WorkbenchChargeDone.class);
                now.setAction(1);
                now.setTaskEndTime(null);
                now.setId(ESUtil.getUUID());
                now.setCreateTime(ESUtil.getNumberDateTime());
                now.setProcessStartTime(new Date());
                now.setTaskCreateTime(new Date());
                now.setCurrentAssignees(now.getCurrentAssignees().replace(orignAssignee, nowAssignee));
                now.setSubmitter(SysUtil.getCurrentUserInfo().getLoginCode());
                now.setUserId(nowAssignee);
                now.setModifier(SysUtil.getCurrentUserInfo().getLoginCode());
                now.setModifyTime(ESUtil.getNumberDateTime());
                saveOrUpdateList.add(now);
                newTasks.add(now);
            }
        }
        try {
            // 批量发送新待办
            if (!newTasks.isEmpty()) {
                sendGTJob(newTasks, 1);
            }
            // 批量关闭旧待办
            if (!finishedTasks.isEmpty()) {
                finishGTJob(finishedTasks);
            }
            // 批量保存变更
            workbenchChargeDoneDao.saveOrUpdateBatch(saveOrUpdateList);
        } catch (Exception e) {
            log.error("任务转派过程中发生异常", e);
            throw new BusinessException("任务转派失败，请重试");
        }
    }

    /**
     * 回滚多个任务的任务转派操作
     * @param taskIdList 待回滚的任务ID集合
     * @param orignAssignee 原处理人
     * @param nowAssignee 当前处理人
     */
    @Override
    public void rollbackChangeAssignessAll(String taskId,Set<String> taskIdList, String orignAssignee, String nowAssignee) {
        log.info("开始回滚任务转派，taskIdList={}, originAssignee={}, nowAssignee={}", taskIdList, orignAssignee, nowAssignee);
        // taskIdList 都是已办
        taskIdList.remove(taskId);
        List<WorkbenchChargeDone> oldTasksToRecover = new ArrayList<>();
        List<WorkbenchChargeDone> tasksToSendGTJob = new ArrayList<>();

        // 查询当前用户的新待办（action=1） 代办现在只有一个
        BoolQueryBuilder nowQuery = QueryBuilders.boolQuery();
        nowQuery.must(QueryBuilders.termQuery("taskId.keyword", taskId));
        nowQuery.must(QueryBuilders.termQuery("action", 1));
        nowQuery.must(QueryBuilders.termQuery("userId.keyword", nowAssignee));
        List<WorkbenchChargeDone> nows = workbenchChargeDoneDao.getListByQuery(nowQuery);
        if (CollectionUtils.isEmpty(nows)) {
            throw new BinaryException("最新待办未找到，taskId=" + taskId);
        }
        WorkbenchChargeDone now = nows.get(0);
        // 查询原始用户的已办记录（action=2）
        BoolQueryBuilder orignQuery = QueryBuilders.boolQuery();
        orignQuery.must(QueryBuilders.termsQuery("taskId.keyword", taskIdList));
        orignQuery.must(QueryBuilders.termQuery("action", 2));
        List<WorkbenchChargeDone> origins = workbenchChargeDoneDao.getListByQuery(orignQuery);
        if (CollectionUtils.isEmpty(origins)) {
            throw new BinaryException("原始待办未找到，taskId=" + taskId);
        }
        for (WorkbenchChargeDone origin : origins) {
            origin.setAction(1); // 恢复为待办
            origin.setTaskEndTime(null); // 清除完成时间
            oldTasksToRecover.add(origin);
            tasksToSendGTJob.add(origin);
        }
        try {
            // 批量删除新待办
            workbenchChargeDoneDao.deleteById(now.getId());
            // 批量删除门户中的新待办
            deleteGTTodoJob(Arrays.asList(now));
            // 批量恢复旧待办
            workbenchChargeDoneDao.saveOrUpdateBatch(oldTasksToRecover);
            // 批量发送门户待办给原用户
            sendGTJob(tasksToSendGTJob, 1);
        } catch (Exception e) {
            log.error("回滚任务过程中发生异常", e);
            throw new BusinessException("任务回滚失败，请重试");
        }
    }


    /**
     * 沟通 关闭原代办-增加新沟通代办
     * @param taskIdList
     * @param orignAssignee
     * @param nowAssignee
     */
    @Override
    public void closeAndAddCommunicate(Set<String> taskIdList, String orignAssignee, String nowAssignee,Long communicateId) {
        log.info("开始处理任务转派，taskIdList={}, originAssignee={}, nowAssignee={}", taskIdList, orignAssignee, nowAssignee);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termsQuery("taskId.keyword", taskIdList));
        boolQueryBuilder.must(QueryBuilders.termQuery("action", 1));

        List<WorkbenchChargeDone> origns = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        if (CollectionUtils.isEmpty(origns)) {
            throw new BinaryException("原待办未找到");
        }

        List<WorkbenchChargeDone> saveOrUpdateList = new ArrayList<>();
        List<WorkbenchChargeDone> newTasks = new ArrayList<>();
        List<WorkbenchChargeDone> finishedTasks = new ArrayList<>();

        for (WorkbenchChargeDone origin : origns) {
            origin.setAction(2);
            origin.setTaskEndTime(new Date());
            saveOrUpdateList.add(origin);
            finishedTasks.add(origin);

            if (origin.getUserId().equals(orignAssignee)) {
                WorkbenchChargeDone now = EamUtil.copy(origin, WorkbenchChargeDone.class);
                String processInstanceName = now.getProcessInstanceName();
                now.setProcessInstanceName("沟通-" + processInstanceName);
                now.setAction(1);
                now.setTaskEndTime(null);
                now.setId(ESUtil.getUUID());
                now.setCreateTime(ESUtil.getNumberDateTime());
                now.setProcessStartTime(new Date());
                now.setTaskCreateTime(new Date());
                now.setCurrentAssignees(now.getCurrentAssignees().replace(orignAssignee, nowAssignee));
                now.setSubmitter(SysUtil.getCurrentUserInfo().getLoginCode());
                now.setUserId(nowAssignee);
                now.setModifier(SysUtil.getCurrentUserInfo().getLoginCode());
                now.setModifyTime(ESUtil.getNumberDateTime());
                now.setCommunicateId(communicateId);
                saveOrUpdateList.add(now);
                newTasks.add(now);
            }
        }
        try {
            // 批量发送新待办
            if (!newTasks.isEmpty()) {
                sendGTJob(newTasks, 1);
            }
            // 批量关闭旧待办
            if (!finishedTasks.isEmpty()) {
                finishGTJob(finishedTasks);
            }
            // 批量保存变更
            workbenchChargeDoneDao.saveOrUpdateBatch(saveOrUpdateList);
        } catch (Exception e) {
            log.error("任务转派过程中发生异常", e);
            throw new BusinessException("任务转派失败，请重试");
        }
    }

    /**
     * 单个沟通记录维护
     * @param taskId
     * @param communicatePromoter
     * @param communicateUser
     */
    public void addCommunicate(String taskId, String communicatePromoter, String communicateUser) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("taskId.keyword", taskId));
        boolQueryBuilder.must(QueryBuilders.termQuery("action",1));
        boolQueryBuilder.must(QueryBuilders.termQuery("userId.keyword", communicatePromoter));
        List<WorkbenchChargeDone> origns = workbenchChargeDoneDao.getListByQuery(boolQueryBuilder);
        if (CollectionUtils.isEmpty(origns)) {
            throw new BinaryException("原待办未找到");
        }
        WorkbenchChargeDone orign = origns.get(0);
        WorkbenchChargeDone now = EamUtil.copy(orign, WorkbenchChargeDone.class);
        now.setId(ESUtil.getUUID());
        now.setCreateTime(ESUtil.getNumberDateTime());
        now.setProcessStartTime(new Date());
        now.setTaskCreateTime(new Date());
        now.setCurrentAssignees(now.getCurrentAssignees().replace(communicatePromoter, communicateUser));
        now.setSubmitter(SysUtil.getCurrentUserInfo().getLoginCode());
        now.setUserId(communicateUser);
        now.setModifier(SysUtil.getCurrentUserInfo().getLoginCode());
        now.setModifyTime(ESUtil.getNumberDateTime());
        if (now.getProcessInstanceName().contains("沟通")) {
            now.setProcessInstanceName(now.getProcessInstanceName().replace("沟通-", ""));
        }
        orign.setAction(2);
        orign.setTaskEndTime(new Date());
        workbenchChargeDoneDao.saveOrUpdateBatch(Arrays.asList(orign, now));
        sendGTJob(Arrays.asList(now), 1);
        finishGTJob(Arrays.asList(orign));
    }


    @Override
    public void rollbackChangeAssigness(String taskId, String orignAssignee, String nowAssignee) {
        BoolQueryBuilder nowQuery = QueryBuilders.boolQuery();
        nowQuery.must(QueryBuilders.termQuery("taskId.keyword", taskId));
        nowQuery.must(QueryBuilders.termQuery("action",1));
        nowQuery.must(QueryBuilders.termQuery("userId.keyword", nowAssignee));
        List<WorkbenchChargeDone> nows = workbenchChargeDoneDao.getListByQuery(nowQuery);
        if (CollectionUtils.isEmpty(nows)) {
            throw new BinaryException("最新待办未找到");
        }
        WorkbenchChargeDone now = nows.get(0);
        BoolQueryBuilder orignQuery = QueryBuilders.boolQuery();
        orignQuery.must(QueryBuilders.termQuery("taskId.keyword", taskId));
        orignQuery.must(QueryBuilders.termQuery("action",2));
        orignQuery.must(QueryBuilders.termQuery("userId.keyword", orignAssignee));
        List<WorkbenchChargeDone> origns = workbenchChargeDoneDao.getListByQuery(orignQuery);
        if (CollectionUtils.isEmpty(origns)) {
            throw new BinaryException("原始待办未找到");
        }
        WorkbenchChargeDone orign = origns.get(0);
        orign.setAction(1);
        workbenchChargeDoneDao.deleteById(now.getId());
        //删除门户现待办
        deleteGTTodoJob(Arrays.asList(now));

        workbenchChargeDoneDao.saveOrUpdate(orign);
        //删除门户原已办
        deleteGTDoneJob(Arrays.asList(orign));
        //重新给门户原已办 发待办
        sendGTJob(Arrays.asList(orign), 1);
    }

    @Override
    public WorkbenchChargeDone getById(Long id) {
        return workbenchChargeDoneDao.getById(id);
    }

    @Override
    public void cirCulate(List<WorkbenchChargeDone> workbenchChargeDoneList) {
        if (CollectionUtils.isEmpty(workbenchChargeDoneList)) {
            return;
        }
        for (WorkbenchChargeDone workbenchChargeDone : workbenchChargeDoneList) {
            workbenchChargeDone.setId(ESUtil.getUUID());
            workbenchChargeDone.setDomainId(1L);
            workbenchChargeDone.setCreateTime(ESUtil.getNumberDateTime());
            workbenchChargeDone.setModifyTime(ESUtil.getNumberDateTime());
        }
        sendGTJob(workbenchChargeDoneList, 2);
        workbenchChargeDoneDao.saveOrUpdateBatch(workbenchChargeDoneList);
    }

    @Override
    public void finishCirCulate(Long id) {
        WorkbenchChargeDone workbenchChargeDone = getById(id);
        if (workbenchChargeDone == null) {
            return;
        }
        workbenchChargeDone.setAction(2);
        workbenchChargeDone.setModifyTime(ESUtil.getNumberDateTime());
        workbenchChargeDone.setTaskEndTime(new Date());
        workbenchChargeDoneDao.saveOrUpdate(workbenchChargeDone);

        finishGTJob(Collections.singletonList(workbenchChargeDone));
    }
}
